package com.qianniu.napi.admin.web.user;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.MconfigExtMapper;
import com.qianniu.napi.admin.mapper.UserExtMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.*;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenxuebin
 * @since 2017-02-24
 */
@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private UserExtMapper userExtMapper;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IXnbiService xnbiService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private ICzfanService czfanService;
    @Autowired
    private IMconfigExtService mconfigExtService;
    @Autowired
    private IFenxiaoService fenxiaoService;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private MconfigExtMapper mconfigExtMapper;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IAccountFlowService accountFlowService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IMaccountService maccountService;
    @Autowired
    private IMaccountFlowService maccountFlowService;
    @Autowired
    private IQnpay qnpay;
    @Autowired
    private IMerchantAppService merchantAppService;
    @Autowired
    private IHealthService healthService;
    @Autowired
    private IGoodsService goodsService;

    @RequestMapping("/api/user/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = userService.selectPage(page, new EntityWrapper<User>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/user/modify")
    @ResponseBody
    public Jinfo userUpdate(HttpServletRequest req,
                            User user) {
        Jinfo info = new Jinfo();
        if(user.getId()==null){
            user.setId(ObjectUtil.getUid());
        }
        user.setModifytime(new Date());
        user.updateById();
        redisService.delUser(ObjectUtil.getUid());
        return info;
    }

    @RequestMapping("/api/user/detail")
    @ResponseBody
    public Jinfo getUserDetailById(@RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        User user = userService.selectById(id);
        info.setInfo(user);
        return info;
    }

    @RequestMapping("/api/user/info")
    @ResponseBody
    public Jinfo userinfo(@RequestParam("feilds") String feilds, @RequestParam("t") String t,
                          @RequestParam(value = "uv", required = false) Long uversion,
                          @RequestParam(value = "sid", required = false) Long sid,
                          @RequestParam(value = "vid", required = false) Long vid,
                          @RequestParam(value = "extra", required = false) String extra,
                          HttpServletRequest req) {
        Jinfo info = new Jinfo();
        try {
            Long mpid = ObjectUtil.getMpid();
            Long uid = vid;
            if (uid == null) uid = ObjectUtil.getUid();
            String guid = ObjectUtil.getGuid();
            BigDecimal zero = new BigDecimal(0);
            String sqlSelect = feilds;
            logger.debug("--------------------------------------user/info=uid=" + uid);
            logger.debug("======feilds=" + feilds);
            logger.debug("======extra=" + extra);
//            if (Strings.isNullOrEmpty(feilds) || feilds.indexOf("id,") >= 0) sqlSelect =  feilds;
            if (feilds.indexOf("is_mch") < 0) sqlSelect += ",is_mch isMch";
            if (feilds.indexOf("is_platform") < 0) sqlSelect += ",is_platform isPlatform";
            if (feilds.indexOf("is_agent") < 0) sqlSelect += ",is_agent isAgent";
            sqlSelect += ",member_level memberLevel,mid,mpid,asmpid,sid,utype,nick_name nickName,avatar_pic avatarPic";
            if (feilds.indexOf("id,") < 0) sqlSelect += ",id";
            if (feilds.indexOf("phone,") < 0) sqlSelect += ",phone";

            Wrapper<User> wrapper = new EntityWrapper<User>().setSqlSelect(sqlSelect);
            if (uid != null) wrapper.eq("id", uid);
            else wrapper.eq("guid", guid);
            User user = userService.selectOne(wrapper);
            if (user == null) {
                info.setCode(4);
                return info;
            }
            user.setId(uid);
            MerchantApp mapp = redisService.getMApp();
            User ruser = redisService.getUser();
            Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                    .eq("hytype", user.getUtype())
                    .eq("mpid", mpid)
            );

            if (fenxiao != null && user != null) {
                int mlevel = user.getMemberLevel();
                user.setHyname(user.getMemberLevel() == 1 ? fenxiao.getFxname1() :
                        mlevel == 2 ? fenxiao.getFxname2() :
                                mlevel == 3 ? fenxiao.getFxname3() :
                                        mlevel == 4 ? fenxiao.getFxname4() :
                                                mlevel == 5 ? fenxiao.getFxname5() :
                                                        mlevel == 6 ? fenxiao.getFxname6() :
                                                                mlevel == 7 ? fenxiao.getFxname7() : "");
            }

            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("jifen") >= 0) {
                Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().setSqlSelect("id,total").eq("uid", uid));
                if (jifen == null) {
                    jifen = new Jifen();
                    jifen.setTotal(zero);
                    jifen.setFanliing(zero);
                    jifen.setRemark("create by /api/user/info");
                    jifen.setUid(uid);
                    jifen.setCreatetime(new Date());
                    jifen.setMid(ObjectUtil.getMid());
                    jifen.setMpid(ObjectUtil.getMpid());
                    jifen.setVersion(1l);
                    jifen.setHuafei(0);
                    jifen.insert();
                    user.setJifen(jifen.getTotal());
                } else {
                    user.setJifen(jifen.getTotal());
                }
            }
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("store") >= 0 && user.getSid() != null && user.getSid() > 0) {
                // 一个商机可能有多个实体店===待完善
                Store store = storeService.selectById(user.getSid());
                if (store != null) {
                    user.setStore(store);
                }
            }
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("acout") >= 0) {
                // 一个商机可能有多个实体店===待完善
                Account acout = accountService.selectOne(new EntityWrapper<Account>()
                        .setSqlSelect("uid,amount,mamount")
                        .eq("uid", user.getId()));
                if (acout != null) {
                    user.setAmount(acout.getAmount().add(acout.getMamount()));
                }
            }
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("token") >= 0) {
                logger.debug("======to generate token");
                String key = null;
                String token = null;
                logger.debug("===========================ready createkey user=" + JSON.toJSONString(user));
                logger.debug("===========================ready createkey ruser=" + JSON.toJSONString(ruser));
                if (user.getIsMch() != ruser.getIsMch() || user.getIsPlatform() != ruser.getIsPlatform()
                        || user.getIsAgent() != ruser.getIsAgent()) {
                    logger.debug("===========================ready createkey user.getMpid()=" + user.getMpid());
                    logger.debug("===========================ready createkey user.getAsmpid()=" + user.getAsmpid());
                    if (user.getMpid() != null && user.getAsmpid() != null && user.getMpid().intValue() != user.getAsmpid().intValue()) {
                        logger.debug("--------------------------------------api/user/info ready createkey user=" + JSON.toJSONString(user));
                        key = !Strings.isNullOrEmpty(user.getPhone()) ? ObjectUtil.getAsmkey(user) : ObjectUtil.getKey(user, user.getMpid());
                        info.setSid(user.getSid());
                    } else {
                        logger.debug("===========================ready createkey why$$$$$$$$$$$$$");
                        key = ObjectUtil.getKey(user);
                    }
                    token = AesUtil.encrypt(key, Constants.ENCODE_KEY);
                    info.setToken(token);

                    redisService.del(t);
                    redisService.set(token, key);
                    info.setToken(token);
                    logger.debug("======generate ok key=" + key);
                    logger.debug("======generate ok token=" + token);
                }
            }
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("oem") >= 0) {
                info.setOem(redisService.getOem(ObjectUtil.getMpid(), guid));
            }
            MconfigExt mconfigExt = mconfigExtMapper.selectById(mpid);
            if (uversion == null) uversion = 1l;
            // 判断开通积分充值功能
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("jfgouwu") >= 0
                    && mconfigExt != null
                    && uversion != null && uversion.longValue() <= mconfigExt.getVersion().longValue()) {
                if (mconfigExt != null && mconfigExt.getJfgouwu() != null && mconfigExt.getJfgouwu() == 1) {
                    user.setJfgouwu(1);
                }
            }
            // 判断是否开通线上提现功能
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("onlinetx") >= 0) {
                if (mconfigExt != null && mconfigExt.getOnlinetx() != null && mconfigExt.getOnlinetx() == 1) {
                    user.setOnlinetx(1);
                }
            }
            // 判断是否开通线下提现功能
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("offlinetx") >= 0) {
                if (mconfigExt != null && mconfigExt.getOfflinetx() != null && mconfigExt.getOfflinetx() == 1) {
                    user.setOfflinetx(1);
                }
            }
            // 判断是否开通在线充值
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("chongzhi") >= 0
                    && mconfigExt != null
                    && uversion != null && uversion.longValue() <= mconfigExt.getVersion().longValue()) {
                if (mconfigExt != null && mconfigExt.getChongzhi() != null && mconfigExt.getChongzhi() == 1) {
                    user.setChongzhi(1);
                }
            }
            // 判断是否开通商家入驻
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("ruzhu") >= 0) {
                if (mconfigExt != null && mconfigExt.getRuzhu() != null && mconfigExt.getRuzhu() == 1) {
                    user.setRuzhu(1);
                }
            }
            // 判断是否开通发布功能
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("fabu") >= 0) {
                if (mconfigExt != null && mconfigExt.getFabu() != null && mconfigExt.getFabu() == 1) {
                    user.setFabu(1);
                }
            }
            // mtype商家类型
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("mtype") >= 0) {
                if (ruser.getSid() != null) {
                    Store store = storeService.selectById(ruser.getSid());
                    info.setData(store == null ? null : store.getType());
                }
            }
            // 商家应用客服电话
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("kefu1") >= 0) {
                user.setKefu1(mapp.getKefu1());
            }
            // 用户健康信息是否登记
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("healthinfo") >= 0) {
                // type:统计类型@0：信息录入；1：打卡(一天一次)；2：进出登记
                Health base = healthService.selectOne(new EntityWrapper<Health>()
                        .eq("type", 0)
                        .eq("uid", uid)
                        .eq("mpid", ObjectUtil.getMpid()));
                info.setData(base);//基本信息
                Health daka = healthService.selectOne(new EntityWrapper<Health>()
                        .eq("type", 1)
                        .eq("statday", DateUtil.getToday())
                        .eq("uid", uid)
                        .eq("mpid", ObjectUtil.getMpid()));
                info.setExtra(daka);//打卡信息

                if (sid != null && sid > 0) {
                    Store store = storeService.selectById(sid);
                    if (store != null) {
                        info.setStore(store);
                    }
                }
                if (!Strings.isNullOrEmpty(extra) && extra.indexOf("hiqrcode") >= 0) {
//                    String path = "/pages/myymtxq/myymtxq?sid=2493&type=2&vid="+uid;
                    String path = "/pages/myymtzhou/myymtzhou?type=2&vid=" + uid;
                    info.setQr(AesUtil.encrypt(path, mapp.getAeskey(), mapp.getAesiv()));
                }
            }
            // 获取商家积分收款码
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("jfskma") >= 0 && user.getIsMch() != null && user.getIsMch().intValue() == 1) {
                if (Strings.isNullOrEmpty(ruser.getJfskma())) {
                    String ywid = "0";
                    String color = "#000000";
                    int width = 300;
                    int touming = 0;


                    String path = Constants.WX_MQR_PATH.replace("MCODE", mapp.getMcode()).replace("MPCODE", mapp.getMpcode());
                    HttpUtil.checkDirectory(path);
                    path = path + uid + "_jfzhifu_" + width + "_" + ywid + ".png";
                    // scene format //uid+page+act+ywid
                    String scene = uid.toString() + "_jfzhifu_Q_" + ywid;
                    // 统一用无限制带参二维码
                    String page = "pages/jfzhifu/jfzhifu";
                    logger.debug("========================================api/user/info page=" + page);
                    logger.debug("========================================api/user/info scene=" + scene);
                    logger.debug("========================================api/user/info width=" + width);
                    String qr = HttpUtil.getminiQr(redisService.getWxtoken(), path, page, scene, width, false, color, touming == 1);
                    logger.debug("==========qr=" + qr);
                    user.setJfskma(qr);
                    ruser.setJfskma(qr);
                    String rkey = Constants.REDIS_APP_USER + mpid + "_" + uid;
                    redisService.set(rkey, ruser, 30, TimeUnit.MINUTES);
                } else {
                    user.setJfskma(ruser.getJfskma());
                }
            }
            // 获取商家积分收款码
            if (!Strings.isNullOrEmpty(extra) && extra.indexOf("goods") >= 0 && user.getIsMch() != null && user.getIsMch().intValue() == 1) {
                int gcout = goodsService.selectCount(new EntityWrapper<Goods>().eq("sid", user.getSid()).eq("type", 0).eq("state", 1));
                info.setCout(gcout);
            }

            info.setInfo(user);
        } catch (Exception e) {
            logger.error("--------------------------------------api/user/info", e);
            info.setCode(5);
            info.setMsg(e.getMessage());
        }
        return info;
    }

    @RequestMapping("/api/user/changeid")
    @ResponseBody
    public Jinfo changeid(@RequestParam("phone") String phone, @RequestParam("pwd") String pwd, @RequestParam("t") String t) {
        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(phone) || Strings.isNullOrEmpty(pwd)) {
            info.setCode(1);
            info.setMsg("账号或密码不能为空");
            return info;
        }

        try {
            Long mpid = ObjectUtil.getMpid();
            String password = AesUtil.encrypt(pwd, Constants.ENCODE_PWD_KEY);

            Wrapper<User> wrapper = new EntityWrapper<User>().setSqlSelect("id,guid,nick_name nickName,avatar_pic avatarPic,mid,mpid,sid,subsid")
                    .eq("password", password)
                    .eq("phone", phone).eq("mpid", mpid);
            User user = userService.selectOne(wrapper);

            Wrapper<User> wrapper2 = new EntityWrapper<User>().setSqlSelect("id,guid,nick_name nickName,avatar_pic avatarPic,mid,mpid,sid,subsid")
                    .eq("password", password)
                    .eq("username", phone).eq("mpid", mpid);
            User user2 = userService.selectOne(wrapper2);
            if (user == null && user2 == null) {
                info.setCode(1);
                info.setMsg("账号密码有误");
                return info;
            }
            if (user == null) user = user2;

            logger.debug("----------------------------to generate token user=" + JSON.toJSONString(user));

            String key = ObjectUtil.getKey(user);
            String token = AesUtil.encrypt(key, Constants.ENCODE_KEY);
            redisService.del(t);
            redisService.set(token, key);
            info.setToken(token);
            user.setMid(null);
            user.setMpid(null);
            user.setSid(null);
            user.setSubsid(null);
            info.setInfo(user);
            logger.debug("======generate ok key=" + key);
            logger.debug("======generate ok token=" + token);

        } catch (Exception e) {
            logger.error("--------------------------------------api/user/changeid", e);
            info.setCode(5);
            info.setMsg(e.getMessage());
        }
        return info;
    }

    //仟牛商户助手登陆
    //登陆其他用户端小程序后台
    @RequestMapping("/api/user/mchlogin")
    @ResponseBody
    public Jinfo shlogin(@RequestParam("phone") String phone,
                         @RequestParam("pwd") String pwd,
                         @RequestParam("v") Integer version,
                         @RequestParam("t") String t) {
        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(t)) {
            info.setCode(1);
            info.setMsg("请求非法");
            return info;
        }
        if (Strings.isNullOrEmpty(phone) || Strings.isNullOrEmpty(pwd)) {
            info.setCode(1);
            info.setMsg("账号或密码不能为空");
            return info;
        }

        try {
            Long mpid = ObjectUtil.getMpid();
            String password = AesUtil.encrypt(pwd, Constants.ENCODE_PWD_KEY);

            Wrapper<User> wrapper = new EntityWrapper<User>()
                    .setSqlSelect("id,guid,nick_name nickName,avatar_pic avatarPic,mid,mpid,sid,subsid,is_staff isStaff,is_admin isAdmin")
                    .eq("password", password)
                    .eq("phone", phone)
                    .ne("mpid", mpid)
                    .isNotNull("mpid").isNotNull("username").isNotNull("password");
            User user = userService.selectOne(wrapper);

            Wrapper<User> wrapper2 = new EntityWrapper<User>()
                    .setSqlSelect("id,guid,nick_name nickName,avatar_pic avatarPic,mid,mpid,sid,subsid,is_staff isStaff,is_admin isAdmin")
                    .eq("password", password)
                    .eq("username", phone)
                    .ne("mpid", mpid)
                    .isNotNull("mpid").isNotNull("username").isNotNull("password");

            User user2 = userService.selectOne(wrapper2);
            if (user == null && user2 == null) {
                info.setCode(1);
                info.setMsg("账号密码有误");
                return info;
            }
            if (user == null) user = user2;

            logger.debug("----------------------------shlogin user=" + JSON.toJSONString(user));
            String key = ObjectUtil.getKey(user);
            String token = AesUtil.encrypt(key, Constants.ENCODE_KEY);
            redisService.del(t);
            redisService.set(token, key);
            info.setToken(token);
            info.setGuid(user.getGuid());

            Long mchmpid = user.getMpid();
            user.setMid(null);
            user.setMpid(null);
            user.setSid(null);
            user.setSubsid(null);
            info.setInfo(user);
            logger.debug("======generate ok key=" + key);
            logger.debug("======generate ok token=" + token);

            if (mchmpid != null && version != null && version > 0) {
                MconfigExt mconfigExt = mconfigExtService.selectById(mchmpid);
                if (mconfigExt != null) {
                    info.setExtra(version > mconfigExt.getVersion());
                }
            }
        } catch (Exception e) {
            logger.error("--------------------------------------api/user/changeid", e);
            info.setCode(5);
            info.setMsg(e.getMessage());
        }
        return info;
    }

    @RequestMapping("/api/user/setpmima")
    @ResponseBody
    public Jinfo setPmima(@RequestParam("mima") String mima) {
        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(mima)) {
            info.setCode(4);
            info.setMsg("参数有误");
            return info;
        }
        User user = new User();
        user.setId(ObjectUtil.getUid());
        user.setPaypasswd(mima);
        user.setModifytime(new Date());
        user.updateById();

        return info;
    }

    @RequestMapping("/api/useradd/yuangong")
    @ResponseBody
    public Jinfo addYuangong(@RequestParam("name") String name,
                             @RequestParam("phone") String phone) {
        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(phone)) {
            info.setCode(4);
            info.setMsg("参数有误");
            return info;
        }
        User cuser = redisService.getUser();
        if (cuser.getIsAdmin() != 1) {
            info.setCode(1);
            info.setMsg("无权限操作");
            return info;
        }

        User user = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,is_platform isPlatform,phone")
                .eq("mpid", cuser.getMpid())
                .eq("phone", phone));

        if (user == null) {
            info.setCode(4);
            info.setMsg("该用户未绑定客户端小程序");
            return info;
        } else {
            if (cuser.getIsPlatform() == 1) {
                user.setUtype(Hytype.platform.getVal());
                user.setIsPlatform(1);
            }
            if (cuser.getIsMch() == 1) {
                user.setUtype(Hytype.merchant.getVal());
                user.setIsMch(1);
            }
            if (cuser.getIsAgent() == 1) {
                user.setUtype(Hytype.agent.getVal());
                user.setIsAgent(1);
            }

            user.setName(name);
            if (cuser.getSid() != null) user.setSid(cuser.getSid());
            MerchantApp mapp = redisService.getMApp();
            String username = mapp.getMpcode() + phone.substring(7);
            String pwd = mapp.getMpcode() + phone.substring(3, 7);
            logger.debug("----------------------------------username=" + username);
            logger.debug("----------------------------------pwd=" + pwd);
            user.setUsername(username);
            user.setPassword(AesUtil.encrypt(pwd, Constants.ENCODE_PWD_KEY));
            user.setModifytime(new Date());
            user.setModifier(cuser.getId());

            user.updateById();
            redisService.delUser(user.getId());
        }

        return info;
    }

    @RequestMapping("/api/user/guanliansj")
    @ResponseBody
    public Jinfo guanliansj(@RequestParam("zhensuo") String company,
                            @RequestParam("name") String name,
                            @RequestParam("phone") String phone,
                            @RequestParam("sid") Long sid
    ) {
        Jinfo info = new Jinfo();
        User user = new User();
        User cuser = redisService.getUser();
        user.setId(ObjectUtil.getUid());
        user.setUsername(name);
        user.setPhone(phone);
        user.setSid(sid);
        user.setMultisid(cuser.getMultisid());
        user.setIsMch(1);
        user.setUtype(Hytype.merchant.getVal());
        user.setModifytime(new Date());
        user.updateById();

        String surkey = Constants.REDIS_STORE_USER + sid;
        // 一个店铺默认关联一个用户
        redisService.set(surkey, user);

        return info;
    }

    @RequestMapping("/api/user/guanliansh")
    @ResponseBody
    public Jinfo guanliansh(@RequestParam("sid") Long sid, @RequestParam("type") Integer type) {
        Jinfo info = new Jinfo();

        String srkey = Constants.REDIS_STORE_USER + sid;
        Store store = storeService.selectById(sid);
        if (store == null) {
            info.setCode(4);
            info.setMsg("该商家不存在");
            return info;
        }

        if (type == 1) {
            // 通过
            User user = redisService.get(srkey);
            if (user != null) {
                user.setIsMch(1);
                user.setUtype(Hytype.merchant.getVal());
                if (user.getSid() == null) user.setSid(sid);
                user.setMultisid(user.getMultisid() == null ? sid.toString() : user.getMultisid() + ";" + sid.toString());
                user.setModifytime(new Date());
                user.updateById();
                redisService.del(srkey);

                Store nstore = new Store();
                nstore.setId(sid);
                nstore.setUid(user.getId());
                nstore.updateById();
            }
        } else {
            // 拒绝
            redisService.del(srkey);
        }

        return info;
    }

    @RequestMapping("/api/user/setquanxian")
    @ResponseBody
    public Jinfo setquanxian(String phone, int utype, int mlevel) {
        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(phone)) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }
        int cout = userService.selectCount(new EntityWrapper<User>().setSqlSelect("id").eq("phone", phone));
        if (cout == 0) {
            info.setCode(1);
            info.setMsg("找不到该手机号注册的用户");
            return info;
        }
        User currentuser = redisService.getUser();
        if (currentuser.getIsPlatform() != 1) {
            info.setCode(1);
            info.setMsg("当前用户无权限操作");
            return info;
        }

        User cuser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,mid,mpid,sid,utype")
                .eq("phone", phone).eq("phone", phone)
                .eq("mpid", currentuser.getMpid()));
        String sn = StringUtil.getSnNo("AR");
        Boolean flag = false;
        if (utype == 0) {// 普通用户授权
            Czfan czfan = czfanService.selectOne(new EntityWrapper<Czfan>()
                    .eq("mpid", ObjectUtil.getMpid())
                    .eq("level", mlevel));

            // 返积分
            if (czfan != null && czfan.getFanjifen().doubleValue() > 0) {
                JifenFlow jf = new JifenFlow();
                jf.setNum(czfan.getFanjifen());//充值金额（元）取整

                jf.setSn(sn);
                jf.setIsConfirm(1);
                jf.setState(1);
                jf.setIotype(IotypeEnum.input.getVal());//积分+
                jf.setJftype(JftypeEnum.recharge.getVal());//积分返消费
                jf.setCreatetime(new Date());
                jf.setUid(cuser.getId());
                jf.setMid(cuser.getMid());
                jf.setMpid(cuser.getMpid());
                jf.setRemark("管理员手动升级会员奖励积分");
                jf.insert();

                while (jf != null && !flag) {
                    Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", cuser.getId()));
                    if (jifen == null) {
                        jifen = initJifen(cuser.getId(), cuser.getMid(), cuser.getMpid());
                    }

                    long version = jifen.getVersion();
                    BigDecimal total = jifen.getTotal();
                    Jifen njifen = new Jifen();
                    njifen.setTotal(jf.getIotype() == 1 ? total.add(jf.getNum()) : total.subtract(jf.getNum()));
                    njifen.setModifytime(new Date());
                    njifen.setModifier(cuser.getId());
                    njifen.setVersion(version + 1);

                    flag = jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", cuser.getId()).eq("version", version));
                    logger.debug(">>>jifenService.update flag=" + flag);
                    if (flag) jf.insertOrUpdate();
                }
            }
            flag = false;
            // 返币
            if (czfan != null && czfan.getFanbi().doubleValue() > 0) {

                XnbiFlow xnbiFlow = new XnbiFlow();
                xnbiFlow.setNum(czfan.getFanbi());//充值金额（元）取整

                xnbiFlow.setSn(sn);
                xnbiFlow.setIsConfirm(1);
                xnbiFlow.setState(1);
                xnbiFlow.setIotype(IotypeEnum.input.getVal());//积分+
                xnbiFlow.setJftype(JftypeEnum.recharge.getVal());//积分返消费
                xnbiFlow.setCreatetime(new Date());
                xnbiFlow.setUid(cuser.getId());
                xnbiFlow.setMid(cuser.getMid());
                xnbiFlow.setMpid(cuser.getMpid());
                xnbiFlow.setRemark("管理员手动升级会员奖励币");
                xnbiFlow.insert();

                while (!flag) {
                    Xnbi xnbi = xnbiService.selectOne(new EntityWrapper<Xnbi>().eq("uid", cuser.getId()));
                    if (xnbi == null) {
                        xnbi = initXnbi(cuser.getId(), cuser.getMid(), cuser.getMpid());
                    }

                    long version = xnbi.getVersion();
                    BigDecimal total = xnbi.getTotal();

                    Xnbi nxnbi = new Xnbi();
                    nxnbi.setTotal(xnbiFlow.getIotype() == 1 ? total.add(xnbiFlow.getNum()) : total.subtract(xnbiFlow.getNum()));
                    nxnbi.setModifytime(new Date());
                    nxnbi.setModifier(xnbi.getUid());
                    nxnbi.setVersion(version + 1);

                    flag = xnbiService.update(nxnbi, new EntityWrapper<Xnbi>().eq("uid", cuser.getId()).eq("version", version));
                    logger.debug(">>>xnbiService.update flag=" + flag);
                    if (flag) xnbiFlow.insertOrUpdate();
                }
            }

            // 处理充值返券，券再支付成功确认后，才分配到用户账户
            if (czfan.getFanquan() > 0 && czfan.getQuanshu() > 0) {
                CouponTpl ctpl = couponTplService.selectById(czfan.getFanquan());
                logger.debug("--------------------------------------===ctpl =" + ctpl);

                for (int i = 0; i < czfan.getQuanshu(); i++) {
                    if (ctpl == null) {
                        logger.error("======couponTpl is null for id=" + czfan.getFanquan());
                        break;
                    }
                    Coupon coupon = new Coupon();
                    coupon.setIsUnused(1);//未使用
                    coupon.setIsUsed(0);//已使用
                    coupon.setIsForever(ctpl.getIsForever());//永久有效
                    coupon.setIsOutdate(0);//已过期
                    coupon.setState(1);

                    coupon.setMid(cuser.getMid());
                    coupon.setMpid(cuser.getMpid());
                    coupon.setUid(cuser.getId());
                    coupon.setSid(ctpl.getSid());
                    coupon.setCreatetime(new Date());

                    coupon.setTplid(ctpl.getId());
                    coupon.setType(ctpl.getType());
                    coupon.setName(ctpl.getName());
                    coupon.setSlogo(ctpl.getSlogo());
                    coupon.setSname(ctpl.getSname());
                    coupon.setRemark(ctpl.getRemark());

                    coupon.setCno(StringUtil.getQuanCode(cuser.getMid()));
                    coupon.setSn(sn);

                    coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
                    coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
                    coupon.setCost(ctpl.getCost());
                    coupon.setUsemin(ctpl.getUsemin());
                    coupon.setOriginType(Qgettype.chongzhi.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值&

                    coupon.insert();
                }
                logger.debug("-------------------------------------czfan.getQuanshu() =" + czfan.getQuanshu());

                if (ctpl != null) {
                    ctpl.setUse(ctpl.getUse() + czfan.getQuanshu());
                    ctpl.updateById();
                }
            }

            if (czfan.getLevel() != null && czfan.getLevel() > 0) {

                Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                        .eq("hytype", cuser.getUtype())
                        .eq("mpid", cuser.getMpid())
                );
                User ouser = userService.selectById(cuser.getId());
                // 充值级别小于当前级别 不处理
                if (czfan.getLevel() >= ouser.getIsMember()) {

                    User user = new User();
                    user.setId(cuser.getId());
                    user.setMemberLevel(czfan.getLevel());
                    user.setDiscount(czfan.getLevel() == 1 ? fenxiao.getMzhekou1() :
                            czfan.getLevel() == 2 ? fenxiao.getMzhekou2() :
                                    czfan.getLevel() == 3 ? fenxiao.getMzhekou3() :
                                            czfan.getLevel() == 4 ? fenxiao.getMzhekou4() :
                                                    czfan.getLevel() == 5 ? fenxiao.getMzhekou5() :
                                                            czfan.getLevel() == 6 ? fenxiao.getMzhekou6() :
                                                                    czfan.getLevel() == 7 ? fenxiao.getMzhekou7() : new BigDecimal(100));
                    user.setDiscount(user.getDiscount().divide(new BigDecimal(100)));
                    user.setIsMember(1);
                    user.setIsEcashCard(1);
                    user.setModifytime(new Date());
                    user.updateById();

                    redisService.delUser(user.getId());
                }
            }

        } else if (utype == 1) {// 商家授权
            if (cuser.getSid() == null || cuser.getSid() <= 0) {
                info.setCode(1);
                info.setMsg("当前用户没有入住店铺，无法升级商家会员");
                return info;
            }
            cuser.setIsMch(1);
            cuser.setUtype(Hytype.merchant.getVal());
        } else if (utype == 2) {
            // 代理人授权
            cuser.setIsAgent(1);
            cuser.setUtype(Hytype.agent.getVal());
        } else if (utype == 3) {
            // 平台用户授权
            cuser.setIsPlatform(1);

            Merchant merchant = merchantService.selectById(ObjectUtil.getMid());
            // 标注是贴牌用户
            if (merchant.getAgentlevel() != null && merchant.getAgentlevel() == 9) cuser.setIsOem(1);

            cuser.setIsPlatform(1);
            cuser.setIsStaff(1);
            if (mlevel == 9) {
                cuser.setIsAdmin(1);
            }
        } else {
            info.setCode(1);
            info.setMsg("不支持当前操作");
            return info;
        }
        cuser.setMemberLevel(mlevel);
        cuser.updateById();

        return info;
    }

    //权限设置
    //mlevel=0时，设置商家员工|代理员工|平台员工
    @RequestMapping("/api/user/setquanxian2")
    @ResponseBody
    public Jinfo setquanxian2(String phone, int utype, int mlevel,
                              @RequestParam(value = "name", required = false) String name) {
        Jinfo info = new Jinfo();
        if (Strings.isNullOrEmpty(phone)) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }
        int cout = userService.selectCount(new EntityWrapper<User>().setSqlSelect("id").eq("phone", phone));
        if (cout == 0) {
            info.setCode(1);
            info.setMsg("找不到该手机号注册的用户");
            return info;
        }
        User currentuser = redisService.getUser();
        if (currentuser.getIsAdmin().intValue() != 1 && utype != Hytype.agent.getVal()) {
            info.setCode(1);
            info.setMsg("当前用户无权限操作");
            return info;
        }

        User cuser = userService.selectOne(new EntityWrapper<User>()
                .setSqlSelect("id,mid,mpid,sid,leagueid,utype,phone,nick_name nickName,avatar_pic avatarPic,is_staff isStaff,is_admin isAdmin,is_agent isAgent")
                .eq("phone", phone)
                .eq("mpid", currentuser.getMpid()));
        if (cuser == null) {
            info.setCode(1);
            info.setMsg("该用户未成功绑定手机号");
            return info;
        }
        if (cuser.getIsAgent() == 1 && utype == Hytype.agent.getVal()) {
            info.setCode(1);
            info.setMsg("该用户已授权开通代理权限");
            return info;
        }

        String sn = StringUtil.getSnNo("AR");
        Boolean flag = false;
        if (utype == Hytype.member.getVal()) {//用户级授权
            Czfan czfan = czfanService.selectOne(new EntityWrapper<Czfan>()
                    .eq("mpid", ObjectUtil.getMpid())
                    .eq("level", mlevel));

            // 返积分
            if (czfan != null && czfan.getFanjifen().doubleValue() > 0) {
                JifenFlow jf = new JifenFlow();
                jf.setNum(czfan.getFanjifen());//充值金额（元）取整

                jf.setSn(sn);
                jf.setIsConfirm(1);
                jf.setState(1);
                jf.setIotype(IotypeEnum.input.getVal());//积分+
                jf.setJftype(JftypeEnum.recharge.getVal());//积分返消费
                jf.setCreatetime(new Date());
                jf.setUid(cuser.getId());
                jf.setMid(cuser.getMid());
                jf.setMpid(cuser.getMpid());
                jf.setRemark("管理员手动升级会员奖励积分");
                jf.insert();

                while (jf != null && !flag) {
                    Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", cuser.getId()));
                    if (jifen == null) {
                        jifen = initJifen(cuser.getId(), cuser.getMid(), cuser.getMpid());
                    }

                    long version = jifen.getVersion();

                    Jifen njifen = new Jifen();
                    njifen.setTotal(jf.getIotype() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum()));
                    njifen.setModifytime(new Date());
                    njifen.setModifier(cuser.getId());
                    njifen.setVersion(version + 1);

                    flag = jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", cuser.getId()).eq("version", version));
                    logger.debug(">>>jifenService.update flag=" + flag);
                    if (flag) jf.insertOrUpdate();
                }
            }
            flag = false;
            // 返币
            if (czfan != null && czfan.getFanbi().doubleValue() > 0) {

                XnbiFlow xnbiFlow = new XnbiFlow();
                xnbiFlow.setNum(czfan.getFanbi());//充值金额（元）取整

                xnbiFlow.setSn(sn);
                xnbiFlow.setIsConfirm(1);
                xnbiFlow.setState(1);
                xnbiFlow.setIotype(IotypeEnum.input.getVal());//积分+
                xnbiFlow.setJftype(JftypeEnum.recharge.getVal());//积分返消费
                xnbiFlow.setCreatetime(new Date());
                xnbiFlow.setUid(cuser.getId());
                xnbiFlow.setMid(cuser.getMid());
                xnbiFlow.setMpid(cuser.getMpid());
                xnbiFlow.setRemark("管理员手动升级会员奖励币");
                xnbiFlow.insert();

                while (!flag) {
                    Xnbi xnbi = xnbiService.selectOne(new EntityWrapper<Xnbi>().eq("uid", cuser.getId()));
                    if (xnbi == null) {
                        xnbi = initXnbi(cuser.getId(), cuser.getMid(), cuser.getMpid());
                    }

                    long version = xnbi.getVersion();
                    BigDecimal total = xnbi.getTotal();

                    Xnbi nxnbi = new Xnbi();
                    xnbi.setTotal(xnbiFlow.getIotype() == 1 ? total.add(xnbiFlow.getNum()) : total.subtract(xnbiFlow.getNum()));
                    nxnbi.setModifytime(new Date());
                    nxnbi.setModifier(xnbi.getUid());
                    nxnbi.setVersion(version + 1);

                    flag = xnbiService.update(nxnbi, new EntityWrapper<Xnbi>().eq("uid", cuser.getId()).eq("version", version));
                    logger.debug(">>>xnbiService.update flag=" + flag);
                    if (flag) xnbiFlow.insertOrUpdate();
                }
            }

            // 处理充值返券，券再支付成功确认后，才分配到用户账户
            if (czfan != null && czfan.getFanquan() > 0 && czfan.getQuanshu() > 0) {
                CouponTpl ctpl = couponTplService.selectById(czfan.getFanquan());
                logger.debug("--------------------------------------===ctpl =" + ctpl);

                for (int i = 0; i < czfan.getQuanshu(); i++) {
                    if (ctpl == null) {
                        logger.error("======couponTpl is null for id=" + czfan.getFanquan());
                        break;
                    }
                    Coupon coupon = new Coupon();
                    coupon.setIsUnused(1);//未使用
                    coupon.setIsUsed(0);//已使用
                    coupon.setIsForever(ctpl.getIsForever());//永久有效
                    coupon.setIsOutdate(0);//已过期
                    coupon.setState(1);

                    coupon.setMid(cuser.getMid());
                    coupon.setMpid(cuser.getMpid());
                    coupon.setUid(cuser.getId());
                    coupon.setSid(ctpl.getSid());
                    coupon.setCreatetime(new Date());

                    coupon.setTplid(ctpl.getId());
                    coupon.setType(ctpl.getType());
                    coupon.setName(ctpl.getName());
                    coupon.setSlogo(ctpl.getSlogo());
                    coupon.setSname(ctpl.getSname());
                    coupon.setRemark(ctpl.getRemark());

                    coupon.setCno(StringUtil.getQuanCode(cuser.getMid()));
                    coupon.setSn(sn);

                    coupon.setStarttime(ctpl.getValidType() == 1 ? DateUtil.getToday() : ctpl.getStarttime());
                    coupon.setEndtime(ctpl.getIsForever() == 1 ? null : ctpl.getValidType() == 1 ? DateUtil.addToday(ctpl.getExpire()) : ctpl.getEndtime());
                    coupon.setCost(ctpl.getCost());
                    coupon.setUsemin(ctpl.getUsemin());
                    coupon.setOriginType(Qgettype.chongzhi.getVal());//领券来源@1：领取；2：分享；3：赠送;4：充值&

                    coupon.insert();
                }
                logger.debug("--------------------------------------===czfan.getQuanshu() =" + czfan.getQuanshu());

                if (ctpl != null) {
                    ctpl.setUse(ctpl.getUse() + czfan.getQuanshu());
                    ctpl.updateById();
                }
            }

            if (czfan != null && czfan.getLevel() != null && czfan.getLevel() > 0) {

                Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                        .eq("hytype", cuser.getUtype())
                        .eq("mpid", cuser.getMpid())
                );
                User ouser = userService.selectById(cuser.getId());
                // 充值级别小于当前级别 不处理
                if (czfan.getLevel() >= ouser.getIsMember()) {

                    User user = new User();
                    user.setId(cuser.getId());
                    user.setMemberLevel(czfan.getLevel());
                    user.setDiscount(czfan.getLevel() == 1 ? fenxiao.getMzhekou1() :
                            czfan.getLevel() == 2 ? fenxiao.getMzhekou2() :
                                    czfan.getLevel() == 3 ? fenxiao.getMzhekou3() :
                                            czfan.getLevel() == 4 ? fenxiao.getMzhekou4() :
                                                    czfan.getLevel() == 5 ? fenxiao.getMzhekou5() :
                                                            czfan.getLevel() == 6 ? fenxiao.getMzhekou6() :
                                                                    czfan.getLevel() == 7 ? fenxiao.getMzhekou7() : new BigDecimal(100));
                    user.setDiscount(user.getDiscount().divide(new BigDecimal(100)));
                    user.setIsMember(1);
                    user.setIsEcashCard(1);
                    user.setName(name);
                    user.setModifytime(new Date());
                    user.updateById();
                }
            }

            cuser.setUtype(Hytype.member.getVal());
        } else if (utype == Hytype.merchant.getVal()) {
            //商家级授权
            cuser.setIsMch(1);
            cuser.setIsStaff(1);
            cuser.setSid(currentuser.getSid());
            cuser.setName(name);
            cuser.setUtype(Hytype.merchant.getVal());

        } else if (utype == Hytype.agent.getVal()) {// 代理人(盟主)授权
            cuser.setIsAgent(1);
            cuser.setName(name);
            cuser.setUtype(Hytype.agent.getVal());
            //if (mlevel == 0) cuser.setIsStaff(1);
            if (ObjectUtil.getMpid() == 11) {
                JifenFlow jf = new JifenFlow();
                jf.setNum(new BigDecimal(300));//充值金额（元）取整

                jf.setSn(sn);
                jf.setIsConfirm(1);
                jf.setState(1);
                jf.setIotype(IotypeEnum.input.getVal());//积分+
                jf.setJftype(JftypeEnum.share.getVal());//积分返消费
                jf.setCreatetime(new Date());
                jf.setUid(currentuser.getId());
                jf.setMid(currentuser.getMid());
                jf.setMpid(currentuser.getMpid());
                jf.setRemark("推开发展推客会员奖励积分");
                jf.insert();

                while (jf != null && !flag) {
                    Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", currentuser.getId()));
                    if (jifen == null) {
                        jifen = initJifen(currentuser.getId(), currentuser.getMid(), currentuser.getMpid());
                    }

                    long version = jifen.getVersion();

                    Jifen njifen = new Jifen();
                    njifen.setTotal(jf.getIotype() == 1 ? jifen.getTotal().add(jf.getNum()) : jifen.getTotal().subtract(jf.getNum()));
                    njifen.setModifytime(new Date());
                    njifen.setModifier(currentuser.getId());
                    njifen.setVersion(version + 1);

                    flag = jifenService.update(njifen, new EntityWrapper<Jifen>().eq("uid", currentuser.getId()).eq("version", version));
                    logger.debug(">>>jifenService.update flag=" + flag);
                    if (flag) jf.insertOrUpdate();
                }
            }
            currentuser.setLeagueid(redisService.getLeagueid());
        } else if (utype == Hytype.guide.getVal()) {// 导购用户授权
            cuser.setUtype(Hytype.guide.getVal());
            cuser.setName(name);
            if (mlevel == 0) cuser.setIsStaff(1);
        } else if (utype == Hytype.platform.getVal()) {// 平台用户授权
            cuser.setIsPlatform(1);
            cuser.setName(name);
            Merchant merchant = merchantService.selectById(ObjectUtil.getMid());
            if (merchant.getAgentlevel() != null && merchant.getAgentlevel() == 9) cuser.setIsOem(1);
            cuser.setUtype(Hytype.platform.getVal());
            if (mlevel == 0) cuser.setIsStaff(1);
            if (mlevel == 9) {
                cuser.setIsAdmin(1);
            }
        } else if (utype == Hytype.jiedanyuan.getVal()) {// 接单员授权
            if (cuser.getIsStaff() != null && cuser.getIsStaff() == 1) {
                info.setCode(1);
                info.setMsg("该用户已经是接单员");
                return info;
            }
            cuser.setName(name);
            cuser.setIsStaff(1);
            cuser.setName(currentuser.getNickName());

            //添加接单员审核信息
            Order order = new Order();
            order.setOrderNo(StringUtil.getSnNo("JDY"));

            order.setState(1);
            order.setOrderType(1);
            order.setGtype(0);
            order.setType(0);
            order.setPayType(0);
            order.setGoodsName("管理员开通接单员");
            order.setGoodsNumber(1);
            order.setPrices(new BigDecimal(0));
            order.setTotal(new BigDecimal(0));

            order.setStatus(StatusEnum.finish.getVal());
            order.setXftype(XftypeEnum.jyajin.getVal());
            order.setUid(cuser.getId());
            order.setMid(cuser.getMid());
            order.setMpid(cuser.getMpid());
            order.setSid(cuser.getSid());
            Store store = redisService.getStore(cuser.getSid());
            order.setSname(store == null ? null : store.getName());

            order.setPhone(cuser.getPhone());
            order.setLinkman(cuser.getNickName());
            order.setHeadimg(cuser.getAvatarPic());
            order.setRealpay(new BigDecimal(0));
            order.setCreatetime(new Date());
            order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
            order.insert();
        } else {
            info.setCode(1);
            info.setMsg("不支持当前操作");
            return info;
        }
        cuser.setIsMember(1);
        cuser.setMemberLevel(mlevel);
        BigDecimal zhekou = fenxiaoService.getMzhekou(cuser);
        cuser.setDiscount(zhekou == null ? new BigDecimal(1) : zhekou);
        cuser.updateById();

        redisService.delUser(cuser.getId());

        return info;
    }

    /*
     * @page 分享打开页
     * @ywid 业务数据
     * @width 二维码宽度
     */
    @RequestMapping("/api/user/myqr")
    @ResponseBody
    public Jinfo myqr(@RequestParam(value = "page", required = false) String page,
                      @RequestParam(value = "ywid", required = false) String ywid,
                      @RequestParam(value = "width", required = false) Integer width,
                      @RequestParam(value = "touming", required = false) Integer touming,
                      @RequestParam(value = "color", required = false) String color,
                      @RequestParam(value = "extra", required = false) String extra
    ) {
        Jinfo jinfo = new Jinfo();
        if (Strings.isNullOrEmpty(page)) page = "index";
        if (Strings.isNullOrEmpty(ywid)) ywid = "";
//        if (Strings.isNullOrEmpty(color)) color = "#000000";
        if (width == null) width = 160;
        if (touming == null) touming = 1;

        MerchantApp mapp = redisService.getMApp();
        String path = Constants.WX_MQR_PATH.replace("MCODE", mapp.getMcode()).replace("MPCODE", mapp.getMpcode());
        HttpUtil.checkDirectory(path);
        path = path + ObjectUtil.getUid() + "_" + page + "_" + width + "_" + ywid + ".png";
        String uid = ObjectUtil.getUid().toString();
//        String scene //uid+page+act+ywid
//        String scene = uid + "_" + Constants.PAGE_MAP.get(page) + "_Q_" + ywid;
        String scene = uid + "__Q_" + ywid;

        // 统一用无限制带参二维码
        page = "pages/" + page + "/" + page;
        logger.debug("==========api/goods/pyq page=" + page);
        logger.debug("==========api/goods/pyq scene=" + scene);
        logger.debug("==========api/goods/pyq width=" + width);
        String qr = HttpUtil.getminiQr(redisService.getWxtoken(), path, page, scene, width, false, color, touming == 1);
        logger.debug("==========qr=" + qr);
        if (!Strings.isNullOrEmpty(extra) &&
                extra.indexOf("phone") >= 0) {
            User user = redisService.getUser();
            jinfo.setExtra(user.getPhone());
        }

//        Goods goods =goodsService.selectOne(new EntityWrapper<Goods>().setSqlSelect("id,pic").eq("id",ywid));
//        String fxpic =Strings.isNullOrEmpty(goods.getPic())?"":goods.getPic().replace("https://img.niucaiduo.com","https://img.niucaiduo.com/fx/"+ObjectUtil.getMid());
//        if(Strings.isNullOrEmpty(fxpic))fxpic = goods.getPic();

//        Map<String,String> map = new HashMap<String,String>();
//        map.put("qr",qr);
//        map.put("fxpic",fxpic);

        jinfo.setInfo(qr);
        return jinfo;
    }

    /*
     * session clear
     */
    @RequestMapping("/api/session/clear")
    @ResponseBody
    public Jinfo sessionClear(
    ) {
        Jinfo jinfo = new Jinfo();
        String rskey = Constants.REDIS_SESSION_KEY + ObjectUtil.getMpid() + "_" + ObjectUtil.getGuid();
        redisService.del(rskey);
        User user = redisService.getUserByGuid(ObjectUtil.getGuid());
        if (user != null && Strings.isNullOrEmpty(user.getOpenid()) && Strings.isNullOrEmpty(user.getAvatarPic())) {
            HttpGet httpget = null;
            try {
                HttpClient httpclient = HttpClients.createDefault();
                httpget = new HttpGet(user.getAvatarPic());
                HttpResponse response = httpclient.execute(httpget);

                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    String content = "httpGet failed,url:" + user.getAvatarPic() + ",http StatusCode:" + response.getStatusLine().getStatusCode();
                    logger.error(content);
                } else {
                    if (response.getFirstHeader("X-ErrNo") != null) {
                        jinfo.setCode(1);//微信图像失效，需要重新登录
                    }
                }
            } catch (Exception e) {
                logger.error("======refreshUser error", e);
            } finally {
                httpget.releaseConnection();
            }
        }
        return jinfo;
    }

    /*
     * session clear
     */
    @RequestMapping("/api/session/stay")
    @ResponseBody
    public Jinfo sessionStay(
    ) {
        Jinfo jinfo = new Jinfo();
        String rskey = Constants.REDIS_SESSION_KEY + ObjectUtil.getMpid() + "_" + ObjectUtil.getGuid();
        String sessionKey = redisService.get(rskey);
        if (!Strings.isNullOrEmpty(sessionKey)) {
            redisService.set(rskey, sessionKey, 7200, TimeUnit.SECONDS);
        }
        return jinfo;
    }

    /*
     * 接单员列表
     */
    @RequestMapping("/api/user/jiedanyuanlist")
    @ResponseBody
    public Jinfo jiedanyuanlist(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                @RequestParam(value = "pageSize", required = false) Integer pageSize
    ) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;

        Page page = new Page(pageIndex, pageSize);
        Page<Order> pages = orderService.selectPage(page, new EntityWrapper<Order>()
                .setSqlSelect("id,linkman,address,phone,status,headimg,uid,realpay,createtime,refundtime")
                .eq("xftype", XftypeEnum.jyajin.getVal())
                .ge("status", 2)
                .orderBy("id", false));
        List<Order> list = pages.getRecords();
        List<String> ids = new ArrayList<String>();
        for (Order item : list) {
            ids.add(item.getUid().toString());
        }
        Map<String, User> umap = new HashMap<String, User>();
        if (ids.size() > 0) {
            List<User> ulist = userService.selectList(new EntityWrapper<User>()
                    .setSqlSelect("id,weixin,phone,xing")
                    .in("id", ids));
            for (User u : ulist) {
                umap.put("user" + u.getId().toString(), u);
            }
            for (Order item : list) {
                User u = umap.get("user" + item.getUid());
                if (u == null) continue;
                UserExt ue = userExtMapper.selectById(item.getUid());
                item.setWeixin(u.getWeixin());
                item.setCarda(ue.getCarda());
                item.setCardb(ue.getCardb());
                item.setCardb(ue.getCardb());
                item.setXingping(u.getXing());
            }
        }
        info.setInfo(list);
        return info;
    }

    /*
     * 接单员信息查询
     */
    @RequestMapping("/api/user/jdyquery")
    @ResponseBody
    public Jinfo jdyquery() {
        Jinfo info = new Jinfo();

        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .setSqlSelect("id,status")
                .eq("xftype", XftypeEnum.jyajin.getVal())
                .eq("uid", ObjectUtil.getUid())
                .ne("is_refund", 1)
                .isNull("refund_no")
        );

        User ruser = redisService.getUser();
        logger.debug("========================================user/jdyquery ruser" + JSON.toJSONString(ruser));
        Map map = new HashMap<String, String>();
        map.put("name", ruser == null ? "" : ruser.getName());
        map.put("phone", ruser == null ? "" : ruser.getPhone());
        map.put("weixin", ruser == null ? "" : ruser.getWeixin());
        UserExt ue = userExtMapper.selectById(ruser.getId());

        map.put("carda", ue == null ? "" : ue.getCarda());
        map.put("cardb", ue == null ? "" : ue.getCardb());

        map.put("status", order == null ? 0 : order.getStatus());
        map.put("money", order == null ? "" : order.getRealpay());
        info.setInfo(map);
        return info;
    }

    /*
     * 接单员审核
     */
    @RequestMapping("/api/user/jdyshenhe")
    @ResponseBody
    public Jinfo jdyshenhe(Long uid, Integer status) {
        Jinfo info = new Jinfo();
        User user = userService.selectById(uid);
        if (status == null || (status != 1 && status != -1)) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }

        if (uid == null || user == null) {
            info.setCode(4);
            info.setMsg("用户不存在");
            return info;
        }

        Map<String, Object> map = null;
        Boolean flag = false;

        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("xftype", XftypeEnum.jyajin.getVal())
                .gt("status", 1)
                .eq("uid", uid)
        );
        if (order == null) {
            info.setCode(1);
            info.setMsg("数据异常审核失败");
            return info;
        }
        //审核通过
        if (status != null && status == 1) {
            order.setStatus(StatusEnum.finish.getVal());
            order.setModifytime(new Date());
            order.setModifier(ObjectUtil.getUid());
            order.updateById();

        } else if (status != null && status == -1) {
            //审核拒绝
            order.setStatus(StatusEnum.finish.getVal());
            order.setModifytime(new Date());
            order.setModifier(ObjectUtil.getUid());
            order.updateById();

            //退押金
            if (Strings.isNullOrEmpty(order.getRefundNo())) {
                order.setRefundNo(StringUtil.getSnNo("R"));
                order.setIsRefund(1);
            }
            // 生成订单取消申请
            OrderRefund or = new OrderRefund();
            or.setRealpay(order.getRealpay());
            or.setRefund(order.getRealpay());
            or.setOid(order.getId());
            or.setOrderNo(order.getOrderNo());
            or.setRefundNo(order.getRefundNo());
            or.setRemark("申请推押金");
            or.setStatus(4);// 默认受理中
            or.setState(1);

            String ip = ObjectUtil.getIP();
            or.setIp(ip);// 默认受理中

            or.setUid(order.getUid());
            or.setMid(order.getMid());
            or.setMpid(order.getMpid());
            or.setCreatetime(new Date());
            or.insert();

            map = qnpay.getRefundmap(order.getMid(), ObjectUtil.getAppid(), order.getOrderNo(), order.getRefundNo(),
                    order.getRealpay(), order.getRealpay(), Constants.REFUND_SOURCE_UNSETTLED_FUNDS);

            if (map == null || !map.containsKey("result_code") || !map.get("result_code").equals("SUCCESS")) {
                map.put("code", 1);
                info.setCode(1);
                info.setMsg("在线退款失败,请后台处理");
            } else {
                //审核拒绝
                order.setIsRefund(1);
                order.setStatus(0);
                order.updateById();

                Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
                AccountFlow af = new AccountFlow();
                af.setRealpay(order.getRealpay());
                af.setDikou(new BigDecimal(0));
                af.setAmount(af.getDikou());

                af.setNickname(user != null ? user.getNickName() : null);
                af.setHeadimg(user != null ? user.getAvatarPic() : null);
                af.setPhone(user != null ? user.getPhone() : null);

                af.setTotal(af.getRealpay().add(af.getAmount()).add(af.getDikou()));

                af.setRemark("取消订单退押金");
                af.setIsConfirm(-1);
                af.setState(1);
                af.setMpid(ObjectUtil.getMpid());
                af.setUid(uid);
                af.setMid(ObjectUtil.getMid());
                af.setTradetime(new Date());
                af.setCreatetime(new Date());
                af.setIotype(IotypeEnum.output.getVal());
                af.setXftype(XftypeEnum.tyajin.getVal());
                af.setSn(order.getRefundNo());
                af.setLasttotal(act.getTotal());
                af.setLastamount(act.getAmount());
                af.insert();

                Account naccount = new Account();

                while (af != null && !flag) {

                    if (act == null) {
                        break;
                    }

                    af.setIsConfirm(1);
                    af.setRuzhang(1);
                    af.setLasttotal(act.getTotal());
                    af.setLastamount(act.getAmount());
                    af.setConfirmDate(new Date());

                    Long version = act.getVersion();
                    BigDecimal total = act.getTotal();
                    BigDecimal yajin = act.getYajin();

                    naccount.setTotal(total.subtract(af.getRealpay()));
                    naccount.setYajin(yajin.subtract(af.getRealpay()));

                    naccount.setModifytime(new Date());
                    naccount.setModifier(uid);
                    naccount.setVersion(version + 1);

                    flag = accountService.update(naccount, new EntityWrapper<Account>()
                            .eq("uid", uid).eq("version", version));
                    if (flag) af.updateById();

                    act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
                }

                //******* 写入[商家退款流水] *******
                MaccountFlow omaf = maccountFlowService.selectOne(new EntityWrapper<MaccountFlow>().eq("sn", order.getOrderNo()));

                MaccountFlow maf = new MaccountFlow();
                maf.setAmount(omaf.getAmount());
                maf.setMamount(omaf.getMamount());

                maf.setState(1);
                maf.setIsConfirm(-1);
                maf.setCreatetime(new Date());
                maf.setTradetime(new Date());
                maf.setIotype(IotypeEnum.output.getVal());
                maf.setXftype(XftypeEnum.refund.getVal());
                maf.setSn(af.getSn());
                maf.setMid(order.getMid());
                maf.setMpid(order.getMpid());
                maf.setUid(uid);
                maf.insert();

                flag = false;
                if (maf != null) {
                    flag = false;
                    Maccount maccount = new Maccount();//接单员审核
                    while (!flag) {
                        Maccount ma = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", order.getMid()));

                        maf.setIsConfirm(1);
                        maf.setLasttotal(ma.getTotal());
                        maf.setConfirmDate(new Date());

                        Long version = ma.getVersion();
                        BigDecimal total = ma.getTotal();
                        BigDecimal amount = ma.getAmount();
                        BigDecimal sale = ma.getSaleAmount();

                        maccount.setTotal(total.subtract(maf.getAmount()));      //总金额
//                        maccount.setSaleAmount(sale.subtract(maf.getAmount()));//累计销售额度，退款，退定金统不计入累计销售额
                        maccount.setAmount(amount.subtract(maf.getAmount()));      //可用余额

                        maccount.setModifytime(new Date());
                        maccount.setModifier(uid);
                        maccount.setVersion(version + 1);

                        maf.setIsConfirm(1);
                        maf.setLasttotal(ma.getTotal());
                        maf.setConfirmDate(new Date());
                        maf.setModifytime(new Date());

                        flag = maccountService.update(maccount, new EntityWrapper<Maccount>().eq("id", ma.getId()).eq("version", version));
                        if (flag) maf.insertOrUpdate();
                    }
                }
            }
        }

        //更新用户信息
        User nuser = new User();
        nuser.setId(uid);
        nuser.setIsStaff(status);
        nuser.updateById();

        redisService.delUser(uid);

        return info;
    }

    public Xnbi initXnbi(Long uid, Long mid, Long mpid) {

        BigDecimal zero = new BigDecimal(0);

        Xnbi act = new Xnbi();
        act.setUid(uid);
        act.setMid(mid);
        act.setMpid(mpid);

        act.setCreatetime(new Date());
        act.setVersion(1l);
        act.setTotal(zero);
        act.setFanliing(zero);
        act.setState(1);
        act.insert();
        return act;
    }

    public Jifen initJifen(Long uid, Long mid, Long mpid) {

        Jifen act = new Jifen();
        BigDecimal zero = new BigDecimal(0);
        act.setUid(uid);
        act.setMid(mid);
        act.setMpid(mpid);

        act.setCreatetime(new Date());
        act.setVersion(1l);
        act.setTotal(zero);
        act.setFanliing(zero);
        act.setState(1);
        act.insert();

        return act;
    }

    //小程序用户列表
    @RequestMapping("/api/user/mplist")
    @ResponseBody
    public Jinfo mplist(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                        @RequestParam(value = "pageSize", required = false) Integer pageSize,
                        HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        Long mpid = ObjectUtil.getMpid();
        page = userService.selectPage(page, new EntityWrapper<User>()
                .setSqlSelect("id,nick_name nickName,avatar_pic avatarPic,is_member isMember,member_level memberLevel,starttime,endtime")
                .isNotNull("openid").eq("mpid", mpid));
        info.setInfo(page.getRecords());
        return info;
    }

    //小程序用户退出登陆
    @RequestMapping("/api/user/logout")
    @ResponseBody
    public Jinfo logout(HttpServletRequest req) {
        Jinfo info = new Jinfo();

        return info;
    }

}
